package com.fafa.yygh.hosp.controller;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fafa.yygh.common.exception.YyghException;
import com.fafa.yygh.common.result.Result;
import com.fafa.yygh.common.utils.MD5;
import com.fafa.yygh.hosp.service.HospitalSetService;
import com.fafa.yygh.model.hosp.Hospital;
import com.fafa.yygh.model.hosp.HospitalSet;
import com.fafa.yygh.vo.hosp.HospitalSetQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @author Sire
 * @version 1.0
 * @date 2022-02-01 15:55
 */
@Api(tags = "医院设置管理")
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
/**
 * 允许跨域访问
 */
//@CrossOrigin
public class HospitalSetController {
    /**
     * 注入Service
     */
    @Autowired
    private HospitalSetService hospitalSetService;

    /**
     * 获取全部医院信息
     *
     * @return
     */
    @ApiOperation(value = "获取所有医院设置")
    @GetMapping("/findAll")
    public Result findAll() {
        List<HospitalSet> list = hospitalSetService.list();
        return Result.ok(list);
    }

    /**
     * 逻辑删除医院信息（通过Id）
     *
     * @param id
     */
    @ApiOperation(value = "逻辑删除医院设置")
    @DeleteMapping("/delById/{id}")
    public Result delById(@PathVariable Long id) {
        boolean flag = hospitalSetService.removeById(id);
        // 操作成功
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 条件查询医院信息（分页）
     * 注意：
     * 因为使用了 @RequestBody(required = false)，所以需要改为Post请求
     * required = false代表这个值可以没有，默认是true
     *
     * @param current            当前页
     * @param limit              页面大小
     * @param hospitalSetQueryVo 查询参数
     * @return
     */
    @ApiOperation(value = "条件查询医院信息（分页）")
    @PostMapping("/findPageHospSet/{current}/{limit}")
    public Result findPageHospSet(@PathVariable int current,
                                  @PathVariable int limit,
                                  @RequestBody(required = false) HospitalSetQueryVo hospitalSetQueryVo) {
        // 分页（记住要导入Mybatis-Plus的jar包）
        Page<HospitalSet> page = new Page(current, limit);
        // 医院名称
        String hosname = hospitalSetQueryVo.getHosname();
        // 医院编号
        String hoscode = hospitalSetQueryVo.getHoscode();
        // 构建条件
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        // 名字不为空
        if (!StringUtils.isEmpty(hosname)) {
            // 这里是模糊查询
            wrapper.like("hosname", hosname);
        }
        // 编号不为空
        if (!StringUtils.isEmpty(hoscode)) {
            // 这里一定要严格等于（因为编号要唯一）
            wrapper.eq("hoscode", hoscode);
        }
        // 分页查询
        Page<HospitalSet> hospitalSetPage = hospitalSetService.page(page, wrapper);
        return Result.ok(hospitalSetPage);
    }

    /**
     * 添加医院设置
     *
     * @param hospitalSet
     * @return
     */
    @ApiOperation(value = "添加医院设置")
    @PostMapping("/saveHospitalSet")
    public Result saveHospitalSet(@RequestBody HospitalSet hospitalSet) {
        // 首先加密生成 SignKey
        Random random = new Random();
        hospitalSet.setSignKey(MD5.encrypt(System.currentTimeMillis() + "" + random.nextInt(1000)));
        // 然后添加信息
        boolean res = hospitalSetService.save(hospitalSet);
        // 返回结果信息
        if (res) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 根据id获取医院设置
     *
     * @param id 查看的id编号
     * @return
     */
    @ApiOperation(value = "根据id获取医院设置")
    @GetMapping("/findHospById/{id}")
    public Result findHospById(@PathVariable Long id) {
        // 模拟异常
        // 如果是自定义异常需要手动try catch一下
        // 注意catch里是exception
        /*try {
            int a = 1 / 0;
        } catch (Exception e) {
            throw new YyghException("失败", 201);
        }*/
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        return Result.ok(hospitalSet);
    }

    /**
     * 修改医院设置
     *
     * @param hospitalSet
     * @return
     */
    @ApiOperation(value = "修改医院设置")
    @PutMapping("/updateHospById")
    public Result updateHospById(@RequestBody HospitalSet hospitalSet) {
//        System.out.println("进入update。。。。");
        boolean flag = hospitalSetService.updateById(hospitalSet);
        // 返回结果信息
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 批量删除医院设置
     *
     * @param idList
     * @return
     */
    @ApiOperation(value = "批量删除医院设置")
    @DeleteMapping("/batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList) {
        boolean flag = hospitalSetService.removeByIds(idList);
        // 返回结果信息
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 锁定和解除医院状态
     *
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "锁定和解除医院状态")
    @PutMapping(value = "/lockHospStatus/{id}/{status}")
    public Result lockHospStatus(@PathVariable Long id,
                                 @PathVariable Integer status) {
        // 先查出用户，然后设置状态值
/*        HospitalSet hospitalSet = hospitalSetService.getById(id);
        hospitalSet.setStatus(status);*/

        // 更改后的，不去查数据库，直接将修改id和参数写到实体类里
        HospitalSet hospitalSet = new HospitalSet();
        hospitalSet.setId(id);
        hospitalSet.setStatus(status);
        // 更新信息（空值不做修改）
        boolean flag = hospitalSetService.updateById(hospitalSet);
        // 返回结果信息
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 发送秘钥签名
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "发送秘钥签名")
    @PutMapping("/sendKey/{id}")
    public Result sendKey(@PathVariable Long id) {
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        String signKey = hospitalSet.getSignKey();
        String hoscode = hospitalSet.getHoscode();
        // TODO 发送短信
        return Result.ok();
    }


}
